﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Db4objects.Db4o;
using NewsMine.DomainObjects;

namespace NewsMine.FeedRepository
{
    public class BaseDataManager : IDisposable
    {
        #region Constructor and IDisposable

        IObjectContainer container = null;

        public BaseDataManager()
        {
            if (container == null)
                container = Db4oEmbedded.OpenFile(RepositoryConfiguration.TargetConfigDataFileName);

            
        }

        public BaseDataManager(IObjectContainer dbContainer)
        {
            if (dbContainer == null)
                throw new ApplicationException("ObjectContainer cannot be null");

            container = dbContainer;
        }

        public void Dispose()
        {
            if (container != null && container.Ext().IsClosed() == false)
            {
                container.Close();
                container.Dispose();
            }
        }

        #endregion


        #region CRUD operations

        public object AddObject(object baseObject)
        {
            if (!(baseObject is BasicInfo))
            {
                throw new ApplicationException("Invalid type to store it into this store.");
            }

            try
            {
                container.Store(baseObject);

                BasicInfo basicInfo = baseObject as BasicInfo;

                basicInfo.ID = container.Ext().GetID(baseObject);

                container.Store(baseObject);

                return basicInfo;
            }
            catch(Exception ex)
            {
                throw ex; //todo:need to handle;
            }
        }

        public bool SaveObject(object baseObject)
        {
            if (!(baseObject is BasicInfo))
            {
                throw new ApplicationException("Invalid type to store it into this store.");
            }

            BasicInfo basicInfo = baseObject as BasicInfo;

            if (basicInfo.ID <= 0)
            {
                throw new ApplicationException("Invalid ID to update to the store");
            }

            try
            {
                container.Store(baseObject);
            }
            catch
            {
                //todo: 

                return false;
            }

            return true;
        }

        public bool DeleteObject(object baseObject)
        {
            throw new ApplicationException();
        }


        #endregion

    }
}
